import React, { Component, PureComponent } from 'react';

class Child extends Component {

  state = {
    otherCount: 0,
    isChangeCount: false,
    y: this.props.obj.y
  }

  // otherCount可能在两处更新，因此不安全
  // UNSAFE_componentWillReceiveProps(newProps) {
  //   console.log('componentWillReceiveProps')
  //   this.state.otherCount = newProps.count
  // }

  // 自定义要不要渲染页面：优化的钩子
  shouldComponentUpdate(nextProps, nextState) {
    // const prevCount = this.props.count
    // const nextCount = nextProps.count
    // return prevCount !== nextCount

    // const newObj = JSON.stringify(nextProps.obj.y)
    // const oldObj = JSON.stringify(nextState.y)
    // console.log(newObj, oldObj)
    // if ( newObj === oldObj) {
    //   return false
    // }
    // return true

    // if(nextProps.obj === this.props.obj) {
    //   return false
    // }
    return true
  }

  // 只要父组件的render run, 子组件的 render 必 run
  render() {
    console.log('child render')
    return (
      <div>
        child {this.props.count} - {this.state.otherCount}
        <br />
        {this.props.obj.x} - {this.props.obj.y}
      </div>
    )
  }

  componentDidMount() {
    console.log('child componentDidMount')
  }

  UNSAFE_componentWillUpdate() {
    console.log('componentWillUpdate')
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('componentDidUpdate')

    // console.log(prevState.otherCount)
    // console.log(this.state.otherCount)

    if (!this.state.isChangeCount) {
      this.setState({
        otherCount: 300,
        isChangeCount: true
      })
    }
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
  }
}

export default Child;